<?php

/**
 * O2O团购PC版本
 * ============================================================================
 * * 版权所有 2009-2016 郑州司科计算机科技有限公司，并保留所有权利。
 * 购买网址: http://www.jzphp.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
  * 咨询电话：400-823-0371 QQ：313999875
 * ============================================================================
 * $Author: zzsike $
 * $Time 2016-02-03 sammy $
*/


require_once(dirname(dirname(__FILE__)) . '/appwap.php');


need_login(true);

$id = abs(intval($_GET['id']));
$num = abs(intval($_GET['quantity']));//用户购买数量
$team = Table::Fetch('team', $id);
$order = Table::Fetch('order', $id,'team_id');
/*修改订单order_check*/
if($order['team_id']==$id && $order['user_id']==$login_user['id'] ){
	$condition=array( 
		'user_id' => $login_user['id'],
		'state' => 'unpay',
		);
	$count = Table::Count('order', $condition);
	$orders = DB::LimitQuery('order',array(
		'condition' => $condition,
		));
	foreach($orders AS $id=>$one){
		$orders[$id] = $one;
		}
	$order = Table::Fetch('order', $id,'team_id');
	$num = $one['quantity'];
}

$money = moneyit($num*$team['team_price']);//总金额

if ( !$team || $team['begin_time']>time() ) {
	Session::Set('error', '团购项目不存在');
	redirect( 'index.php' );
}
team_state($team);
if ($team['close_time']) {
	Session::Set('error', '团购项目已结束，不能再次购买');
	redirect( 'index.php' );
}
/* 查询快递清单 */
if ($team['delivery'] == 'express') {
	$express_ralate = unserialize($team['express_relate']);
	foreach ($express_ralate as $k=>$v) {
		$express[$k] = Table::Fetch('category',$v['id']);
		$express[$k]['relate_data'] = $v['price'];
	}
}
//whether buy
$ex_con = array(
		'user_id' => $login_user_id,
		'team_id' => $team['id'],
		'state' => 'unpay',
		);
$order = DB::LimitQuery('order', array(
	'condition' => $ex_con,
	'one' => true,
));

//buyonce
if (strtoupper($team['buyonce'])=='Y') {
	$ex_con['state'] = 'pay';
	if ( Table::Count('order', $ex_con) ) {
		Session::Set('error', '您已经成功购买了本单产品，请勿重复购买，快去关注一下其他产品吧！');
		redirect( "now.php"); 
	}
}

//peruser buy count
if ($team['per_number']>0) {
	$now_count = Table::Count('order', array(
		'user_id' => $login_user_id,
		'team_id' => $id,
		'state' => 'pay',
	), 'quantity');
	$team['per_number'] -= $now_count;
	if ($team['per_number']<=0) {
		Session::Set('error', '您购买本单产品的数量已经达到上限，快去关注一下其他产品吧！');
		redirect( 'now.php' ); 
	}
}

//post buy
if ( $_POST ) {
	need_login(true);
	$express_price = (int) $_POST['express_price'];
	$express_id = (int) $_POST['express_id'];
	$condbuy = implode('@', $_POST['condbuy']);
	if ($INI['sms']['cons']=='1') {
		$user = DB::GetQueryResult("SELECT mobile FROM user WHERE id=".$login_user['id']."");//获取用户手机号

		if ($user && !Utility::IsMobile($user['mobile']))
		{
			Session::Set('error', '您必须先绑定手机号才能参加团购，请到<a href="/account/settings.php#bindmobile" target="_blank"><font color="red"><b>这里设置</b></font></a>，绑定手机号后重新参加团购即可！');
			redirect( WEB_ROOT . "/team/buy.php?id={$team['id']}");
		}
		$express_price = abs($ex[$express_id]['price']);
	}	
	$condbuy = implode('@', $_POST['condbuy']);
	$table = new Table('order', $_POST);
	$table->quantity = abs(intval($table->quantity));

	if ( $table->quantity == 0 ) {
		Session::Set('error', '购买数量不能小于1份');
		redirect( "team.php?id={$team['id']}");
	} 
	elseif ( $team['per_number']>0 && $table->quantity > $team['per_number'] ) {
		Session::Set('error', '您本次购买本单产品已超出限额！');
		redirect( "team.php?id={$id}"); 
	}


	if ($order && $order['state']=='unpay') {
		$table->SetPk('id', $order['id']);
	}

	$table->user_id = $login_user_id;
	$table->state = 'unpay';
	$table->allowrefund = $team['allowrefund'];
	$table->team_id = $team['id'];
	$table->city_id = $team['city_id'];
	$table->express = ($team['delivery']=='express') ? 'Y' : 'N';
	$table->fare = $table->express=='Y' ? $express_price : 0;
	$table->express_id = $table->express=='Y' ? $express_id : 0;
	$table->price = $money;//总金额
	$table->price = $team['team_price'];//单价
	$table->credit = 0;
	$table->condbuy = $condbuy;
	
	/*用户收货地址*/
	if ($team['delivery'] == 'express') {
		if( $_POST['address-list'] && $_POST['address-list'] !='0' ){
			$address = Table::Fetch('address',$_POST['address-list']);
			if ($address['user_id'] != $login_user_id ){
				Session::Set('error', '收货地址信息有误');
				redirect( WEB_ROOT . "/team/buy.php?id={$team['id']}");	
			}
			$table->realname = $address['name'];
			$table->zipcode = $address['zipcode'];
			$table->mobile = $address['mobile'];
			$table->address = $address['province']. $address['area']. $address['city']. $address['street'];
		}
	}
	if ( $table->id ) {
			$eorder = Table::Fetch('order', $table->id);
			if ($eorder['state']=='unpay' && $eorder['team_id'] == $id	&& $eorder['user_id'] == $login_user_id ) {
				$table->origin = team_origin($team, $table->quantity,$express_price);
				$table->origin -= $eorder['card'];
			} else {
				$eorder = null;
			}
	}
	if (!$eorder){
		$table->pk_value='';
		$table->create_time = time();
		$table->origin = team_origin($team, $table->quantity,$express_price);
	}

	if ($team['delivery']=='express') {
		if (!$table->address 
			|| !Utility::IsMobile($table->mobile)
			|| !$table->zipcode
			|| !$table->realname
			) {
			Session::Set('error', '购买选项填写不完整');
			Session::Set('loginpagepost', json_encode($_POST));
			redirect("buy.php?id={$team['id']}");
		}
	}
    
	$insert = array(
		'user_id', 'team_id', 'city_id', 'state','express_id', 
		'fare', 'express', 'origin', 'price','express_xx',
		'address', 'zipcode', 'realname', 'mobile', 'quantity',
		'create_time', 'remark','allowrefund','condbuy',
	);
    if($team['allowrefund']=='Y')  {
    	$insert[] = 'allowrefund';
    }
	if ($flag = $table->update($insert)) {
		if ($team['delivery'] == 'express'){
			$msgupdate=array();
			$msgupdate['realname']=$_POST['realname'];
			$msgupdate['mobile']=$_POST['mobile'];
			$msgupdate['address']=$_POST['address'];
			$msgupdate['zipcode']=$_POST['zipcode'];
			DB::Update('user',$login_user_id,$msgupdate);	
			}
	   
		$order_id = abs(intval($table->id));

		/* 插入订单来源 */
		$data['order_id'] = $order_id;
		$data['user_id'] = $login_user_id;
		$data['referer'] = $_COOKIE['referer'];
		$data['create_time'] = time();
		DB::Insert('referer', $data);

		redirect("pay.php?id={$order_id}");
	}
}

//each user per day per buy
if (!$order) { 
	$order = json_decode(Session::Get('loginpagepost'),true);
	settype($order, 'array');
	if ($order['mobile']) $login_user['mobile'] = $order['mobile'];
	if ($order['zipcode']) $login_user['zipcode'] = $order['zipcode'];
	if ($order['address']) $login_user['address'] = $order['address'];
	if ($order['realname']) $login_user['realname'] = $order['realname'];
	$order['quantity'] = 1;
}
//end;

$order['origin'] = team_origin($team, $order['quantity'],$express_price);

if ($team['max_number']>0 && $team['conduser']=='N') {
	$left = $team['max_number'] - $team['now_number'];
	if ($team['per_number']>0) {
		$team['per_number'] = min($team['per_number'], $left);
	} else {
		$team['per_number'] = $left;
	}
}

$city_id = abs(intval($city['id']));
$condition = array(
    'city_id' => $city_id
);
//$partner = Table::Fetch('partner', $city_id,'city_id');

$partner2 = DB::LimitQuery('partner', array(
	'condition' => $condition
));
//print_r($partner);

include template('wap_buy');
